import React, {useEffect, useState} from 'react';
import {
    Button,
    Card,
    Col, Descriptions,
    Drawer,
    Form,
    Input,
    message,
    Modal,
    Row,
    Select,
    Space,
    Table,
    Tag
} from 'antd';
import {DeleteOutlined, EditOutlined, PlusOutlined, ReloadOutlined, SearchOutlined} from '@ant-design/icons';
import {addTemplate, backupTemplate, deleteTemplate, getListTemplateByPage, updateTemplate} from "@/api/template";
import CodeEditor from "@/components/CodeEditor";
import {addProjectTemplateRef, getListProject} from "@/api/project";
import dayjs from "dayjs";
import {statusEnum} from "@/model/enum";
import {tipData} from "@/config";

const Index: React.FC = () => {
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [form] = Form.useForm();
    const [data, setData] = useState<[{id: number, code: string, description: string, sortable: number, status: number, createTime: string, updateTime: string}]>([]);
    const [editingKey, setEditingKey] = useState<number | null>(null);
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        showTotal: (total: number) => `共 ${total} 条`
    });

    // 添加搜索表单
    const [searchForm] = Form.useForm();
    const [drawerOpen, setDrawerOpen] = useState(false);
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const rowSelection = {
        selectedRowKeys,
        onChange: (newSelectedRowKeys: React.Key[]) => {
            setSelectedRowKeys(newSelectedRowKeys);
        },
        selections: [
            {
                key: 'all-data',
                text: '全选数据',
                onSelect: () => {
                    setSelectedRowKeys(data.map((record) => record.id));
                },
            },
            Table.SELECTION_INVERT,
            Table.SELECTION_NONE,
        ]
    }

    const [projectVisible, setProjectVisible] = useState(false);
    const [selectedProjectId, setSelectedProjectId] = useState<number | null>(null);
    const [projectList, setProjectList] = useState<{ value: number; label: string }[]>([]);

    const fetchProjectList = async () => {
        try {
            const res = await getListProject({});
            const result = res.data.map((item) => ({
                value: item.id,
                label: item.name
            }));
            setProjectList(result);
            if (result.length > 0) {
                setSelectedProjectId(result[0].value);
            }
        } catch (e) {
            console.error('获取项目数据失败:', e);
        }
    }

    const handleProjectFinish = () => {
        // 选中项目id+多个模板id实现绑定
        if (!selectedProjectId) {
            message.error('请选择项目');
            return;
        }
        if (selectedRowKeys.length === 0) {
            message.error('请选择模板');
            return;
        }
        try {
            const res = addProjectTemplateRef({
                projectId: selectedProjectId,
                templateId: selectedRowKeys
            })
            message.success('绑定成功');
        } catch (e) {
        } finally {
            setProjectVisible(false);
        }

    };

    useEffect(() => {
        if (projectVisible) {
            fetchProjectList();
        }
    }, [projectVisible]);

    // 获取列表数据
    const fetchData = async (params: { current: number; pageSize: number; code?: string; }) => {
        setLoading(true);
        try {
            const response = await getListTemplateByPage(params);
            if (response.code === 0) {
                setData(response.data.records);
                setPagination({
                    ...pagination,
                    current: params.current,
                    pageSize: params.pageSize,
                    total: response.data.total
                });
            } else {
                message.error(response.message || '获取数据失败');
            }
        } catch (error) {
            message.error('获取数据失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchData({
            current: 1,
            pageSize: 10
        });
    }, []);

    const columns = [
        {
            title: '代码',
            dataIndex: 'code',
            key: 'code',
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
        },
        {
            title: '排序',
            dataIndex: 'sortable',
            key: 'sortable',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status: number) => {
                switch (status) {
                    case 0:
                        return <Tag color="red">禁用</Tag>;
                    case 1:
                        return <Tag color="blue">启用</Tag>;
                    case 2:
                        return <Tag color="green">备份</Tag>;
                    default:
                        return <Tag color="blue">未知</Tag>;
                }
            },
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (text: string) => {
                return text ? dayjs(text).format('YYYY:MM:DD HH:mm:ss') : '--';
            }
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render: (text: string) => {
                return text ? dayjs(text).format('YYYY:MM:DD HH:mm:ss') : '--';
            }
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EditOutlined/>}
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button
                        type="link"
                        danger
                        icon={<DeleteOutlined/>}
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            ),
        },
    ];

    const handleAdd = () => {
        form.resetFields();
        setEditingKey(null);
        setDrawerOpen(true);
    };

    const handleEdit = (record) => {
        form.setFieldsValue(record);
        setEditingKey(record.id);
        setDrawerOpen(true);
    };

    const handleDelete = (id: number) => {
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除这条数据？',
            onOk: async () => {
                try {
                    await deleteTemplate({id: id});
                    message.success('删除成功');
                    if (data.length === 1 && pagination.current > 1) {
                        await fetchData({
                            current: pagination.current - 1,
                            pageSize: pagination.pageSize
                        });
                    } else {
                        await fetchData({
                            current: pagination.current,
                            pageSize: pagination.pageSize
                        });
                    }
                } catch (error) {
                    message.error('删除失败');
                }
            },
        });
    };

    const handleModalOk = async () => {
        try {
            const values = await form.validateFields();
            if (editingKey) {
                const response = await updateTemplate({
                    ...values,
                    id: editingKey,
                });
                if (response.code === 0) {
                    message.success('更新成功');
                    setDrawerOpen(false);
                    await fetchData({
                        current: pagination.current,
                        pageSize: pagination.pageSize
                    });
                } else {
                    message.error(response.message || '更新失败');
                }
            } else {
                const response = await addTemplate(values);
                if (response.code === 0) {
                    message.success('添加成功');
                    setDrawerOpen(false);
                    await fetchData({
                        current: 1,
                        pageSize: pagination.pageSize
                    });
                } else {
                    message.error(response.message || '添加失败');
                }
            }
        } catch (error) {
            message.error('操作失败');
        }
    };

    // 处理搜索
    const handleSearch = async () => {
        const values = await searchForm.getFieldsValue();
        await fetchData({
            code : values.code,
            current: 1,
            pageSize: pagination.pageSize
        });
    };

    // 重置搜索
    const handleReset = () => {
        searchForm.resetFields();
        fetchData({
            current: 1,
            pageSize: pagination.pageSize
        });
    };

    // 修改表格变化处理函数，保留搜索条件
    const handleTableChange = (newPagination: any) => {
        const values = searchForm.getFieldsValue();
        fetchData({
            ...values,
            current: newPagination.current,
            pageSize: newPagination.pageSize
        });
    };

    const onClose = () => {
        setDrawerOpen(false);
    };

    const handleBackup = async () => {
        const res = await backupTemplate({
            ids: selectedRowKeys
        });
        if (res.code === 0) {
            message.success('备份成功');
            await fetchData({
                current: pagination.current,
                pageSize: pagination.pageSize
            });
        } else {
            message.error(res.message || '备份失败');
        }
    }

    return (
        <div>
            <Card>
                <Form
                    form={searchForm}
                    layout="inline"
                    style={{marginBottom: 16}}
                >
                    <Row gutter={16} style={{width: '100%'}}>
                        <Col span={6}>
                            <Form.Item label="代码" name="code">
                                <Input placeholder="请输入代码" allowClear/>
                            </Form.Item>
                        </Col>
                        <Col span={12} style={{textAlign: 'right'}}>
                            <Space>
                                <Button
                                    type="primary"
                                    icon={<SearchOutlined/>}
                                    onClick={handleSearch}
                                >
                                    搜索
                                </Button>
                                <Button
                                    icon={<ReloadOutlined/>}
                                    onClick={handleReset}
                                >
                                    重置
                                </Button>
                                <Button
                                    type="primary"
                                    icon={<PlusOutlined/>}
                                    onClick={handleAdd}
                                >
                                    添加
                                </Button>
                                <Button
                                    color="primary"
                                    variant="outlined"
                                    onClick={()=>{
                                      setProjectVisible(true)
                                    }}
                                >
                                    分配项目
                                </Button>
                                <Button
                                    color="green"
                                    variant="outlined"
                                    onClick={()=>{
                                        Modal.confirm({
                                            title: '确定要备份选中文件吗？',
                                            okText: '确定',
                                            cancelText: '取消',
                                            onOk: async () => {
                                                await handleBackup();
                                            },
                                        });
                                    }}
                                >
                                    备份文件
                                </Button>
                            </Space>
                        </Col>
                    </Row>
                </Form>

                <Table
                    columns={columns}
                    dataSource={data}
                    rowKey="id"
                    pagination={pagination}
                    loading={loading}
                    onChange={handleTableChange}
                    rowSelection={rowSelection}
                />
            </Card>

            <Drawer
                title={`代码模板`}
                placement="right"
                width={'60vw'}
                onClose={onClose}
                open={drawerOpen}
                extra={
                    <Space>
                        <Button onClick={onClose}>取消</Button>
                        <Button type="primary" onClick={handleModalOk}>
                            确认
                        </Button>
                    </Space>
                }
            >
                <Form form={form}>
                    <Form.Item label="代码" name="code">
                        <Input/>
                    </Form.Item>
                    <Form.Item label="描述" name="description">
                        <Input/>
                    </Form.Item>
                    <Form.Item label="排序" name="sortable">
                        <Input/>
                    </Form.Item>
                    <Form.Item label="状态" name="status">
                        <Select options={statusEnum} defaultValue={1} />
                    </Form.Item>
                    <Form.Item label="模板" name="template">
                        <CodeEditor language={'java'}/>
                    </Form.Item>
                    {/*提示一些信息*/}
                    <Card title="以下字段是模板中可以替换的变量" style={{marginTop: 16}}>
                        <Descriptions bordered items={
                            tipData.map(item => ({
                                label: item.label,
                                children: item.value,
                            }))
                        }/>
                    </Card>
                </Form>
            </Drawer>

            <Modal
                visible={projectVisible}
                title="绑定项目"
                width={400}
                onCancel={() => {
                    setProjectVisible(false);
                }}
                footer={[
                    <Button key="cancel" onClick={() => {
                        setProjectVisible(false);
                    }}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" onClick={handleProjectFinish}>
                        确认
                    </Button>,
                ]}
            >
                <Select style={{width: '100%'}} placeholder="请选择项目" value={selectedProjectId} options={projectList}
                        onChange={(value) => {
                            setSelectedProjectId(value);
                        }}>
                </Select>
            </Modal>
        </div>
    );
};

export default Index;